<template>
  <div class="chat-system-container">
    <div class="chat-list-area">
      <!-- 搜索框 -->
      <el-input
        placeholder="搜索"
        prefix-icon="el-icon-search"
        style="width: 100%; margin: 10px 0;"
      >
        <template slot="append">
          <el-button icon="el-icon-plus" circle></el-button>
        </template>
      </el-input>

      <!-- 聊天列表 -->
      <ul class="chat-items">
        <li class="chat-item"
            :class="{ active: item.targetId === activeItemId }"
            v-for="item in sessionListMap.values()"
            :key=item.id
            @click="getTargetSession(item)">
          <el-badge v-if="item.unreadCount !== 0" :value="item.unreadCount>99?99:item.unreadCount" :max="99" class="avatar-badge">
            <el-avatar style="margin-left: 0.2vw" :size="32" src="https://example.com/family.jpg" />
          </el-badge>
          <el-avatar v-else style="margin-left: 0.2vw" :size="32" src="https://example.com/family.jpg" />
          <div class="chat-info">
            <div class="chat-name">
              <p class="name">{{item.sessionName}}</p>
              <p class="time">{{item.lastMessageTime}}</p>
            </div>
            <div class="chat-message" v-if="item.lastMessage !== null">{{item.lastMessage.content}}</div>
          </div>
        </li>
      </ul>
    </div>

    <!-- 右侧聊天窗口-->
    <div class="chat-window" v-if="isShowChatWindow">
      <!-- 对话标题栏 -->
      <div class="window-title-bar">
        <div>
          <span class="group-title">{{targetSession.sessionName}}</span>
        </div>
        <div>
          <div>
            <el-button icon="el-icon-search" type="text" class="title-btn"></el-button>
            <el-button icon="el-icon-minus" type="text" class="title-btn"></el-button>
            <el-button icon="el-icon-full-screen" type="text" class="title-btn"></el-button>
            <el-button icon="el-icon-close" type="text" class="title-btn"></el-button>
          </div>
          <div class="cancel-tubiao-div">
            <div>
            </div>
            <el-button icon="el-icon-more" type="text" class="title-btn more-btn"></el-button>
          </div>
        </div>
      </div>
      <div class="chat-messages" style="flex: 1; padding: 20px; overflow-y: auto; border: 1px solid #e5e5e5;" >
        <!-- messageList 聊天消息内容，这里暂时为空，可根据实际需求动态渲染 -->
        <div class="message-system" v-for="msg in systemMessages" :key="msg.time">
          {{ msg.content }} <span class="time">{{ msg.time }}</span>
        </div>
        <div
          v-for="(msg, index) in messageList"
          :key="index"
          :class="msg.senderId === curUserId ? 'my-message' : 'other-message'"
          class="message-item"
        >
          <!-- 头像 -->
          <img :src="msg.avatar" alt="avatar" class="avatar" />
          <!-- 消息内容 -->
          <div class="content">{{ msg.content }}</div>
        </div>
      </div>
      <div class="sendMessage-div">
        <el-input
          type="textarea"
          :rows="6"
          placeholder="输入消息"
          class="message-input"
          v-model="message"
          @keyup.enter="sendMessage"
        >
          <template slot="prepend">
            <el-button icon="el-icon-smile" circle></el-button>
            <el-button icon="el-icon-folder" circle></el-button>
            <el-button icon="el-icon-scissors" circle></el-button>
            <el-button icon="el-icon-comment" circle></el-button>
          </template>
        </el-input>
        <el-button class="sendMessage-button" type="success" @click="sendMessage(curUserId,targetSession.targetId,targetSession.id)">发送</el-button>
      </div>
    </div>
  </div>

</template>

<script>

import {getFriendSessionListApi,loadCurMessageApi,
  setSessionSelectedStatusApi,updateSessionVOInfoApi,
  setMessageReadApi,updateRedisUnReadInfoApi } from "@/api/system/chat";
import user from "@/store/modules/user";
import {formatDate} from "@/utils";

export default {
  name: 'ChatSystemAdjusted',
  props: {
    userInfo:{}
  },
  data() {
    return {
      curUserId: user.state.id,
      message: '',
      activeItemId: null,  // 初始值设为 null，表示没有选中会话
      targetSessionList:[],
      targetSession: {},
      isShowChatWindow: false,
      messageList: [],
      systemMessages:[],
      sessionListMap: new Map(),
      options:{
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      },
    };
  },
  created() {
    // 获取URL中的用户名参数
    this.curUserId = user.state.id;

    if (!this.curUserId) {
      console.log("@@@ 用户未登录")
      return;
    }
    console.log("第一步：用户：{} 正在连接聊天服务器", this.curUserId)
    this.initWebSocket();
  },
  async mounted() {
    // TODO 加载用户会话列表
    await this.getFriendSessionList(user.state.id)
    if(this.userInfo.userId !== undefined){
      this.activeItemId = this.userInfo.userId;
      this.isShowChatWindow = true;
      for(let i = 0; i < this.targetSessionList.length; i++){
        if(this.targetSessionList[i].targetId === this.userInfo.userId){
          this.targetSession = this.targetSessionList[i];
        }
      }
      let sessionId = this.targetSession.id;
      //TODO  点击“发消息”进来的，查询当前登录用户和好友的消息列表  this.userInfo.userId,user.state.id
      this.loadCurMessage(sessionId);
    }
  },
  methods: {
    initWebSocket() {
      // 根据环境确定WebSocket协议
      const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
      const host = window.location.host;

      // 建立连接
      this.ws = new WebSocket(`${protocol}//${host}:9990/chat/${this.curUserId}`);

      // 连接成功
      this.ws.onopen = () => {
        console.log('第二步：'+this.curUserId + '与WebSocket连接已建立');
      };

      // 接收消息
      this.ws.onmessage = (event) => {
        console.log('第四步：从服务器 chatPage 接收到消息:', event.data)
        const message = JSON.parse(event.data);
        console.log('解析后的message:', message)
        this.handleMessage(message);
      };

      // 连接关闭
      this.ws.onclose = () => {
        console.log('第四步：WebSocket连接已关闭');
        this.systemMessages.push({
          content: '与服务器的连接已断开',
          time: new Date().toLocaleTimeString()
        });
      };

      // 连接错误
      this.ws.onerror = (error) => {
        console.error('WebSocket错误:', error);
        this.systemMessages.push({
          content: '连接出错，请刷新页面重试',
          time: new Date().toLocaleTimeString()
        });
      };
    },
    updateSessionVOInfo(sessionId, receiverId,messageId){
      let obj = {
        id: sessionId,
        userId: receiverId,
        messageId: messageId
      }
      let queryVOJson = JSON.stringify(obj);
      updateSessionVOInfoApi(queryVOJson).then(response => {
        // console.log("@@@ updateSessionVOInfoApi",response);
      })
    },
    // 处理接收到的消息
    handleMessage(message) {

      let sessionId = message.conversationId

      if(this.sessionListMap.has(sessionId)){
        console.log("@@@ handleMessage message:{}",message)
        let newVar = this.sessionListMap.get(sessionId);
        newVar.lastMessage = message;
        newVar.lastMessageTime = message.sendTime.substring(5,16);
        newVar.lastMsgId = message.id;

        if(message.isRead === 0){
          newVar.unreadCount += 1;

          // TODO 调用接口 修改redis中会话未读数  和  session的最后一条消息记录
          this.updateRedisUnReadInfo(sessionId, user.state.id, message.id)
          this.updateSessionVOInfo(sessionId, user.state.id, message.id)
        }
      }


      switch (message.messageType) {
        case 1:
          console.log("@@@ handleMessage：{}", message)
          this.messageList.push(message);

          break;
        //   TODO
        case 'system':
          this.systemMessages.push(message);
          break;
        case 'onlineUsers':
          this.onlineUsers = message.onlineUsers || [];
          break;
        case 'history':
          // 加载历史消息
          try {
            const history = JSON.parse(message.content);
            this.messageList = history;
          } catch (e) {
            console.error('解析历史消息失败', e);
          }
          break;
      }

      // 滚动到最新消息
      this.scrollToBottom();
    },
    // 滚动到最新消息
    scrollToBottom() {
      this.$nextTick(() => {
        const messagesContainer = this.$el.querySelector('.chat-messages');
        if (messagesContainer) {
          messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }
      });
    },
    sendMessage(senderId, receiverId,sessionId) {
      console.log('第三步：sendMessage 发送消息：', this.message);
      if (!this.message.trim() || !this.ws) return;
      // 构造messageVO
      let obj = {
        'conversationId':sessionId,
        'senderId':senderId,
        'receiverId':receiverId,
        'messageType':1,  // 先发送文本
        'content':this.message,
        'senderStatus':0,
        'isRead':0,
        'sendTime':formatDate(new Date()),

        // 'conversationType':1
      }
      let messageVOJson = JSON.stringify(obj);
      console.log('@@@messageVOJson', messageVOJson);
      // sendMessageApi(messageVOJson).then(response => {
      //   // 获取消息列表
      // })
      this.ws.send(messageVOJson);
      this.messageList.push(obj);
      // TODO 处理发送者发送消息后 的会话回显
      if(this.targetSession.id !== null && this.sessionListMap.has(this.targetSession.id)){
        console.log("@@@ sendMessage obj:{}",obj)
        let newVar = this.sessionListMap.get(sessionId);
        newVar.lastMessage = obj;
        newVar.lastMessageTime = obj.sendTime.substring(5,16);
      }
      this.message = ''
    },
    getFriendSessionList(userId) {
      // TODO 获取当前登录用户的会话列表
      return new Promise((resolve, reject) => {
        let obj = {
          userId: userId
        }
        let queryJson = JSON.stringify(obj);
        getFriendSessionListApi(queryJson).then(response => {
          console.log("@@@getFriendSessionList response.data",response.data)
          this.targetSessionList = response.data;
          for (let i = 0; i < this.targetSessionList.length; i++){
            this.sessionListMap.set(this.targetSessionList[i].id,this.targetSessionList[i]);
          }
          this.$set(this,'sessionListMap',new Map(this.sessionListMap))
          resolve();
        })
      })
    },
    getTargetSession(item) {

      if(item.targetId === this.activeItemId){
        return;
      }
      this.activeItemId = item.targetId
      this.setSessionSelectedStatus(this.targetSession===null?'':this.targetSession.id,item.id);

      // TODO 待验证 是否达到效果
      item.unreadCount = 0;

      this.targetSession = item;
      this.isShowChatWindow = true
      // 设置当前用户会话选中信息  this.userInfo.userId,user.state.id
      // TODO 加载当前登录用户与item.id的会话
      let sessionId = this.targetSession.id;
      this.setMessageRead(sessionId,user.state.id);
      this.loadCurMessage(sessionId);
    },
    setMessageRead( sessionId,userId){
      let obj = {
        conversationId: sessionId,
        curUserId: userId
      }
      let queryJson = JSON.stringify(obj);
      setMessageReadApi(queryJson).then(response => {
        // console.log("@@@ setMessageReadApi",response);
      })
    },
    loadCurMessage(sessionId) {
      let obj = {
        conversationId: sessionId
      }
      let queryJson = JSON.stringify(obj);
      loadCurMessageApi(queryJson).then(response => {
        this.messageList = response.data;
      })
    },
    setSessionSelectedStatus(preId,curId){
      let obj = {
        preId: preId,
        curId: curId
      }
      let queryJson = JSON.stringify(obj);
      setSessionSelectedStatusApi(queryJson).then(response => {

      })
    },
    updateRedisUnReadInfo(sessionId, receiverId, messageId) {
      let obj = {
        curUserId: receiverId,
        conversationId: sessionId,
        id: messageId
      }
      let queryJson = JSON.stringify(obj);
      updateRedisUnReadInfoApi(queryJson).then(response => {

      })
    }
  }

};
</script>

<style scoped>
.chat-system-container {
  height: 92vh;
  display: flex;
  width: 100%;
}

.cancel-tubiao-div {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.chat-list-area {
  width: 240px;
  border-right: 1px solid #e5e5e5;
  display: flex;
  flex-direction: column;
  padding: 10px;
}

.chat-items {
  list-style: none;
  padding: 0;
  margin: 0;
  flex: 1;
  overflow-y: auto;
}

.chat-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  cursor: pointer;
}

.chat-item:hover {
  background-color: #f5f5f5;
}

.chat-item.active {
  background-color: #e5e5e5;
}

.chat-info {
  margin-left: 15px;
  width: 100%;
}

.chat-name {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 14px;
}

.name {
  margin: 0; /* 去除 p 标签默认的外边距，使布局更规整 */
}
.time {
  margin: 0;
  padding-right: 0.2vw;
  /* 字体大小，可根据需求调整 */
  font-size: 12px;
  /* 字体颜色，这里设为灰色，可根据设计改色值 */
  color: #999;
  font-family: "Microsoft Yahei", sans-serif;
}

.chat-message {
  font-size: 12px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-window {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.window-title-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  border-bottom: 1px solid #e5e5e5;
}

.group-title {
  font-size: 16px;
  margin-right: 10px;
}

.title-btn {
  margin-left: 5px;
}

.more-btn {
  font-size: 20px;
}

.message-input {
  border-top: 1px solid #e5e5e5;
}

.sendMessage-div{
  display: flex;
  flex-direction: column; /* 设置为垂直方向排列 */
  align-items: flex-end; /* 子元素水平方向靠左对齐，可根据需要改为 flex-end 靠右 */
}

.sendMessage-button{
  margin: 5px;
  width: 80px;
  height: 30px;

  background-color: #2c2f33;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.message-item {
  display: flex;
  margin-bottom: 10px;
  align-items: flex-start; /* 头像与文字顶部对齐 */
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin: 0 10px;
}

/* 自己的消息：左对齐 */
.other-message {
  flex-direction: row; /* 头像在左，内容在右 */
}
.other-message .content {
  background-color: #fff;
  border: 1px solid #e5e5e5;
  border-radius: 10px;
  padding: 8px 12px;
  max-width: 60%;
}

/* 他人的消息：右对齐 */
.my-message {
  flex-direction: row-reverse; /* 头像在右，内容在左 */
}
.my-message .content {
  background-color: #dcf8c6;
  border-radius: 10px;
  padding: 8px 12px;
  max-width: 60%;
}

.message-system {
  text-align: center;
  color: #777;
  margin: 10px 0;
  font-style: italic;
}

.time {
  font-size: 12px;
  margin-left: 10px;
  color: #aaa;
}

</style>

